package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.bean.CmsCategory;
import com.example.demo.mapper.CmsArticleMapper;
import com.example.demo.mapper.CmsCategoryMapper;

@Service
public class CmsCategoryService {
	
	//跟spring容器表明，需要在运行时注入一个XmsCategoryMapper对象进来
	@Autowired
	private CmsCategoryMapper categoryMapper;
	
	@Autowired
	private CmsArticleMapper cmsArticleMapper;
	
	public int deleteById(String id) {
		int num = categoryMapper.selectCountRefPid(id);
		if(num>0) {
			return -1;
		}
		
		num =cmsArticleMapper.selectAtricleCountByCategryId(id);
		if(num>0) {
			return -2;
		}
		
		//如果没有子栏目 ，也没有关联的文章，就删除
		return categoryMapper.deleteByPrimaryKey(id);
	}
	
	/*
	 * 获取所有栏目信息
	 */
	public List<CmsCategory> getAllCategories() {
		//List<CmsCategory> list = categoryMapper.selectAll();
		List<CmsCategory> list = categoryMapper.allCategoryWithPArent();
		if (list!=null) {
			return list;
		}else {
			return new ArrayList<CmsCategory>();
		}
	}
	
	public boolean saveOrUpdateCmsCategory(CmsCategory cmsCategory) {
		
		String pid = cmsCategory.getPid();
		if(pid!=null&&!"".equals(pid)) {
			CmsCategory category= categoryMapper.selectByPrimaryKey(cmsCategory.getPid());
			if(category==null) {
				return false;
			}
		}
		if(cmsCategory.getId()!=null&&!"".equals(cmsCategory.getId())) {
			categoryMapper.updateByPrimaryKey(cmsCategory);
		}else {
			cmsCategory.setId(UUID.randomUUID().toString());
			categoryMapper.insert(cmsCategory);
		}
		return true;
	}
	
	
	public String batchDelete(String[] ids) {
		//定义一个集合，用来记录删除成功的数据
		ArrayList<String> sucArrayList  = new ArrayList<String>();
		//定义一个集合用来记录删除失败的数据
		ArrayList<String> failArrayList  =new ArrayList<String>();
		
		ArrayList<String> noExistArrayList  =new ArrayList<String>();
		if(ids!=null&&ids.length>0) {
		for (String id : ids) {
			int result = deleteById(id);
			if(result ==-1|| result ==-2) {
				failArrayList.add(id);
			}else if (result ==0) {
			noExistArrayList.add(id);
			}else if(result >0) {
				sucArrayList.add(id);
			}
		}
		String str = "success:";
		if (sucArrayList.size()>0) {
			str +="成功删除了"+sucArrayList+"!";
		}
		if (failArrayList.size()>0) {
			str +="请先删除"+failArrayList+"栏目下的子栏目或者文章!";
		}
		if (noExistArrayList.size()>0) {
			str +="栏目"+noExistArrayList+"不存在!";
		}
		
		return str;
	  }else {
		  return "error!!!";
	  }
	}
	

}
